<script setup>
import { BASE_IMT_URL } from '@/config/index.js'
// import imgs from '@/assets/test/WechatIMG27344.jpg'
import { useGraphStore } from '@/store/modules/graphStore.js'
import { isTrueForDict } from '@/utils/dict.js'
import { ditherImageToBase64 } from '@/utils/index.js'
import { computed, inject, onMounted, reactive } from 'vue'
import { getStyles } from './index'

const graphStore = useGraphStore()
const getNode = inject('getNode')
const nodeConfig = reactive({
  nodeData: null,
  value: null,
  styles: {},
  imageDithering: false,
  autoScale: false,
  base64: '',
  isInit: false
})
const updateData = async (nodeData) => {
  const { contentValue, imageDithering, autoScale } = nodeData
  nodeConfig.styles = getStyles(nodeData)
  nodeConfig.imageDithering = imageDithering
  nodeConfig.value = contentValue ? `${BASE_IMT_URL}/${contentValue}` : null
  // nodeConfig.value = imgs
  nodeConfig.autoScale = autoScale
  // 0无抖动 1算法1 2算法2
  nodeConfig.base64 = await ditherImageToBase64({
    url: nodeConfig.value,
    type: imageDithering,
    palette: graphStore.graph.info.color
  })
  nodeConfig.nodeData = nodeData
  nodeConfig.isInit = true
}
const imgSrc = computed(() => {
  // const { imageDithering } = nodeConfig
  return nodeConfig.base64
})
onMounted(() => {
  const node = getNode()
  updateData(node.getData())
  node.on('change:data', ({ current }) => {
    updateData(current)
  })
})
</script>

<template>
  <div
    class="img-node w-full h-full overflow-hidden"
    :style="nodeConfig.styles"
    v-if="nodeConfig.isInit"
  >
    <img
      v-if="!!imgSrc"
      :src="imgSrc"
      alt="img"
      :class="{
        'w-full': isTrueForDict(nodeConfig.autoScale),
        'h-full': isTrueForDict(nodeConfig.autoScale),
      }"
    />
  </div>
</template>

<style scoped lang="less"></style>
